package com.icinfo.cloud.provider.peripheralinterface.taskcenter.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.FileUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.dto.*;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.service.ITaskCenterService;
import com.icinfo.cloud.provider.peripheralinterface.taskcenter.vo.TransferConfigureVo;
import com.icinfo.cloud.provider.punish.common.user.service.IMemberUserCommonService;
import com.icinfo.cloud.provider.punish.usersign.mapper.MemberUserSignMapper;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.model.MemberUserInfo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * 描述：大综合一体化平台接口实现类
 *
 * @Author zhengqiang
 * @Date 2022/8/15 21:45
 **/
@Slf4j
@Service
public class TaskCenterServiceImpl implements ITaskCenterService {

    @Value("${taskCenter.url}")
    private String taskCenterUrl;

    @Value("${taskCenter.api.saveDisposalBackResult}")
    private String saveDisposalBackResultApi;
    @Value("${taskCenter.api.tripartiteStatusByRelUid}")
    private String tripartiteStatusByRelUidApi;
    @Value("${taskCenter.api.getTransferCaseEvidenceBy}")
    private String getTransferCaseEvidenceByApi;
    @Value("${taskCenter.api.importAnnexByTaskId}")
    private String importAnnexByTaskIdApi;
    @Value("${taskCenter.api.saveUserSign}")
    private String saveUserSignApi;
    @Value("${taskCenter.api.saveCaseAutoAddTrabeReBase}")
    private String saveCaseAutoAddTrabeReBaseApi;
    @Value("${taskCenter.api.savePunishCooInfoPush}")
    private String savePunishCooInfoPushApi;
    @Resource
    private MemberUserSignMapper memberUserSignMapper;


    /**
     * 描述： 检查转处罚保存处置回传结果(检查)
     *
     * @author: zhengqiang
     * @date: 2022/8/16
     * @param: dto
     * @return {@link Result}
     **/
    @Override
    public Result saveDisposalBackResult(DisposalBackResultDto dto) {
        log.info("调用检查转处罚保存处置回传结果接口");
        Result result = null;
        try {
            Map<String, String> headers = HeaderUtil.headerInfo();
            //免登获取大综合token
            /*String dzhToken=getDzhToken();
            headers.put("authorization","Bearer "+dzhToken);*/
            String paramStr = JSONObject.toJSONString(dto);
            log.info("saveDisposalBackResult -- 入参: {}", paramStr);
            String response = HttpUtil.createPost(taskCenterUrl.concat(saveDisposalBackResultApi)).addHeaders(headers).body(paramStr).execute().body();
            log.info("saveDisposalBackResult -- 出参: {}", response);
            result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode()){
                return Result.success(Constant.STRING_SUCCESS_EN);
            }
        } catch (Exception e) {
            log.warn("saveDisposalBackResult异常: {}", e);
            e.printStackTrace();
        }
        return Result.error(Constant.STRING_FAIL_EN);
    }
    /**
     * 获取大综合token
     * @author liyafeng
     * @date 2023/9/6
      * @param
     * @return {@link String}
     */
    private String getDzhToken() throws Exception{
        String dzhToken="";
        UserDTO userDTO=UserUtil.getUserInfo();
        Map<String,Object> paramMap=new HashMap<>();
        List<String> userIds = new ArrayList<>();
        userIds.add(userDTO.getUserId().toString());
        paramMap.put("userIds", userIds);
        List<MemberUserInfo> list=memberUserSignMapper.selectMemberUserInfoByUserIds(paramMap);
        String zwdId="";
        if(!ObjectUtils.isEmpty(list)){
            zwdId=list.get(0).getZzdAccountid();
        }
        //获取authCode
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5hlo/O0dNRLXulMwmPtavSiFWgnd3Z25Dk8TCkbDjma2qHJcbXHuWxpKofLmITnvjxDFMhfHp6OVq8XKERrVDMuoWH7FDWMsVgplAcbCu41MeCwqa6bE/5LxxBBIKelQ4Bcj+YQGnvH89N86F/aA+VW0ErHkRdL7zIBKyt+7J5wIDAQAB";
        RSA rsa1 = new RSA(null, publicKey);
        Map<String, String> params = new HashMap<>();
        params.put("accountId", zwdId);
        params.put("sysType", "0");
        params.put("timestamp", System.currentTimeMillis() + "");

        byte[] encrypt = rsa1.encrypt(StrUtil.bytes(mapConcatStr(params), CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        // 生成授权码,http请求头的内容
        String authCode = HexUtil.encodeHexStr(encrypt);
        Map<String, String> paramsMap=new HashMap<>();
        paramsMap.put("code",authCode);
        paramsMap.put("appKey","100000");
        String result=HttpUtils.doGet(taskCenterUrl+"/api/v2/usercenter/sso/login",paramsMap);
        System.out.println("免登接口返回："+result);
        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        if(StringUtils.isNotBlank(code)&& Constant.STRING_200.equals(code)){
            JSONObject jsonObject = resultObject.getJSONObject("data");
            dzhToken=jsonObject.getString("token");
        }else{
            throw new BusinessException("获取大综合token失败");
        }
        return dzhToken;
    }
    /**
     * 连接字符串
     *
     * @param concatMap
     * @return
     */
    public static String mapConcatStr(Map<String, String> concatMap) {
        Iterator<Map.Entry<String, String>> entryIterator = concatMap.entrySet().iterator();
        StringBuilder sb = new StringBuilder();
        while (entryIterator.hasNext()) {
            Map.Entry<String, String> entry = entryIterator.next();
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 【V1.4.1】描述： 修改协同的案件移送状态(协同)
     *
     * @author: zhengqiang
     * @date: 2022/8/22
     * @param: dto
     * @return {@link Result}
     **/
    @Override
    public Result tripartiteStatusByRelUid(TripartiteStatusDto dto) {
        log.info("调用修改案件移送状态接口(协同)");
        Result result = null;
        try {
            //案源类型编码: 0 线索 1 检查 2处罚
            dto.setRelType(Constant.STRING_2);
            dto.setRelName("处罚");

            Map<String, String> headers = HeaderUtil.headerInfo();
           /* String dzhToken=getDzhToken();
            headers.put("authorization","Bearer "+dzhToken);*/
            HashMap paramMap = BaseUtil.javaToMap(dto);
            log.info("tripartiteStatusByRelUid -- 入参: {}", paramMap);
            String response = HttpUtil.createGet(taskCenterUrl.concat(tripartiteStatusByRelUidApi)).addHeaders(headers).form(paramMap).execute().body();
            log.info("tripartiteStatusByRelUid -- 出参: {}", response);
            result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode()){
                return Result.success(Constant.STRING_SUCCESS_EN);
            }
        } catch (Exception e) {
            log.warn("tripartiteStatusByRelUid异常: {}", e);
            e.printStackTrace();
        }
        return Result.error(Constant.STRING_FAIL_EN);
    }

    /**
     * 【V1.4.1】描述： 获取证据材料列表
     *
     * @author: zhengqiang
     * @date: 2022/8/23
     * @param: dto
     * @return {@link TransferConfigureVo}
     **/
    @Override
    public TransferConfigureVo getTransferCaseEvidenceBy(TransferConfigureQueryDto dto) {
        log.info("调用获取证据材料列表接口(协同)");
        Result result = null;
        try {
            Map<String, String> headers = HeaderUtil.headerInfo();
            /*String dzhToken=getDzhToken();
            headers.put("authorization","Bearer "+dzhToken);*/
            HashMap paramMap = BaseUtil.javaToMap(dto);
            log.info("getTransferCaseEvidenceBy -- 入参: {}", dto);
            String response = HttpUtil.createGet(taskCenterUrl.concat(getTransferCaseEvidenceByApi)).addHeaders(headers).form(paramMap).execute().body();
            log.info("getTransferCaseEvidenceBy -- 出参: {}", response);
            result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())){
                TransferConfigureVo configureVo = JSON.parseObject(result.getData().toString(), TransferConfigureVo.class);
                return configureVo;
            }
        } catch (Exception e) {
            log.warn("getTransferCaseEvidenceBy异常: {}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述： 调用上传签名附件接口
     *
     * @author: zhengqiang
     * @date: 2022/9/5
     * @param: ossPath 处罚oss地址
     * @return {@link String}
     **/
    public String importAnnexByTaskId(String ossPath) {
        log.info("调用上传附件接口");
        try {
            InputStream is = HttpUtil.createGet(ossPath).execute().bodyStream();

            HashMap paramMap = new HashMap();
            File file = File.createTempFile("temp", ".jpeg");
            FileUtil.inputStreamToFile(is, file);
            paramMap.put("file", file);
            paramMap.put("source", "PUS");//定死类型 处罚签名

            String response = HttpUtil.createPost(taskCenterUrl.concat(importAnnexByTaskIdApi)).form(paramMap).execute().body();
            log.info("importAnnexByTaskId -- 出参: {}", response);
            Result result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())){
                return result.getData().toString();
            }
        } catch (Exception e) {
            log.warn("importAnnexByTaskId: {}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述： 保存签名
     *
     * @author: zhengqiang
     * @date: 2022/9/8
     * @param: ossPath 处罚oss地址
     * @param: headers
     * @param: userName
     * @return {@link Result}
     **/
    @Override
    public Result saveUserSign(String ossPath, Map headers, String userName) {
        log.info("开始处理保存签名逻辑");
        try {
            String fileUrl = importAnnexByTaskId(ossPath);
            if (ObjectUtils.isEmpty(fileUrl)) {
                return Result.error("上传签名失败");
            }

            SignFileDto fileDto = new SignFileDto();
            fileDto.setFileUrl(fileUrl);
            fileDto.setFileName(userName + "签名.jpeg");
            String paramStr = JSONObject.toJSONString(fileDto);
            log.info("saveUserSign -- 入参: {}", fileDto);
            String response = HttpUtil.createPost(taskCenterUrl.concat(saveUserSignApi)).addHeaders(headers).body(paramStr).execute().body();
            log.info("saveUserSign -- 出参: {}", response);
            Result result = JSONObject.parseObject(response, Result.class);
            return result;
        } catch (Exception e) {
            log.warn("saveUserSign异常: {}", e);
            e.printStackTrace();
        }
        return Result.error("设置签名失败");
    }

    /**
     * 描述： 推送案件到事项抄告
     *
     * @author: zhengqiang
     * @date: 2022/10/19
     * @param: addTrabeReBaseDto
     * @return {@link Result}
     **/
    @Override
    public Result saveCaseAutoAddTrabeReBase(AddTrabeReBaseDto addTrabeReBaseDto) {
        log.info("开始处理推送案件到事项抄告");
        try {
            String paramStr = JSONObject.toJSONString(addTrabeReBaseDto);
            log.info("saveCaseAutoAddTrabeReBase -- 入参: {}", addTrabeReBaseDto);
            String response = HttpUtil.createPost(taskCenterUrl.concat(saveCaseAutoAddTrabeReBaseApi)).body(paramStr).execute().body();
            log.info("saveCaseAutoAddTrabeReBase -- 出参: {}", response);
            Result result = JSONObject.parseObject(response, Result.class);
            return result;
        } catch (Exception e) {
            log.warn("saveCaseAutoAddTrabeReBase: {}", e);
            e.printStackTrace();
        }
        return Result.error("推送案件到事项抄告失败");
    }

    /**
     * 描述： 推送案件到信息协同
     *
     * @author: zhengqiang
     * @date: 2022/10/20
     * @param: punishCooInfoDtoList
     * @return {@link Result}
     **/
    @Override
    public Result savePunishCooInfoPush(PunishCooInfoRequest punishCooInfoRequest) {
        log.info("开始处理推送案件到信息协同");
        try {
            String paramStr = JSON.toJSONString(punishCooInfoRequest);
            log.info("savePunishCooInfoPush -- 入参: {}", paramStr);
            String response = HttpUtil.createPost(taskCenterUrl.concat(savePunishCooInfoPushApi)).body(paramStr).execute().body();
            log.info("savePunishCooInfoPush -- 出参: {}", response);
            Result result = JSONObject.parseObject(response, Result.class);
            return result;
        } catch (Exception e) {
            log.warn("savePunishCooInfoPush: {}", e);
            e.printStackTrace();
        }
        return Result.error("推送案件到信息协同失败");
    }

}
